package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.addCheckGroup(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        if (checkitemIds!=null&&checkitemIds.length!=0){
            addCheckGroup_CheckItem(checkGroupId,checkitemIds);
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    public void update(CheckGroup checkGroup, Integer[] checkitemIds) {
        //修改检查组基本信息
        checkGroupDao.update(checkGroup);
        //清理中间表外键关系
        Integer checkGroupId = checkGroup.getId();
        deletet_checkgroup_checkitemBycheckGroup_id(checkGroupId);
        //重建中间表外键关系
        addCheckGroup_CheckItem(checkGroupId,checkitemIds);
    }

    @Override
    public void deleteById(Integer id) {
        Long count = checkGroupDao.findt_etmeal_checkgroupCountBycheckgroup_id(id);
        if (count!=0){
            throw new RuntimeException("检查套餐有引用项");
        }else {
            deletet_checkgroup_checkitemBycheckGroup_id(id);
            checkGroupDao.deletet_checkgroupById(id);
        }
    }

    //抽取建立中间表外键关系的方法
    public void addCheckGroup_CheckItem(Integer checkGroupId,Integer[] checkitemIds){
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.addCheckGroup_CheckItem(checkGroupId,checkitemId);
        }
    }
    //抽取删除中间表外键关系的方法
    public void deletet_checkgroup_checkitemBycheckGroup_id(Integer checkGroupId){
        checkGroupDao.deletet_checkgroup_checkitemBycheckGroup_id(checkGroupId);
    }
}
